#include "weather_json.h"


#include <QDebug>


weather_json::weather_json(QWidget *parent)
    : QWidget(parent)
{
    // 网络访问对象
    mNetAccessManager = new QNetworkAccessManager(this);
    // 接收数据信号
    connect(mNetAccessManager , &QNetworkAccessManager::finished , this , &weather_json::Network_finished);

}

void weather_json::Network_finished(QNetworkReply *reply)
{
    // 请求头   读取相应码
    int start_code = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toUInt();

    qDebug() << start_code;

    //
    // 读取数据
    QByteArray data = reply->readAll();
    QByteArray bytearr = QString(data).toUtf8();
    processWeatherData(bytearr);

}
QVector<WeatherData> weather_json::handle_json(const QByteArray& bytearr)
{
    QVector<WeatherData> weatherList;

        // 解析JSON
        QJsonDocument doc = QJsonDocument::fromJson(bytearr);
        if (doc.isNull()) {
            qDebug() << "JSON解析失败";
            return weatherList;
        }

        QJsonObject rootObj = doc.object();
        if (rootObj["status"].toInt() != 200) {
            qDebug() << "API返回状态错误";
            return weatherList;
        }

        // 获取当前日期
        QString currentDate = rootObj["date"].toString(); // 格式: 20251010
        QDate today = QDate::fromString(currentDate, "yyyyMMdd");

        // 获取天气预报数组
        QJsonObject dataObj = rootObj["data"].toObject();
        QJsonArray forecastArray = dataObj["forecast"].toArray();

        // 找到今天在数组中的位置
        int todayIndex = -1;
        for (int i = 0; i < forecastArray.size(); ++i) {
            QJsonObject dayObj = forecastArray[i].toObject();
            QString ymd = dayObj["ymd"].toString();
            QDate date = QDate::fromString(ymd, "yyyy-MM-dd");

            if (date == today) {
                todayIndex = i;
                break;
            }
        }

        if (todayIndex == -1) {
            qDebug() << "未找到今天的天气数据";
            return weatherList;
        }

        // 提取从今天开始的7天数据
        for (int i = todayIndex; i < forecastArray.size() && i < todayIndex + 7; ++i) {
            QJsonObject dayObj = forecastArray[i].toObject();
            WeatherData weather;

            weather.week = dayObj["week"].toString();
            weather.type = dayObj["type"].toString();

            // 解析温度字符串
            QString highStr = dayObj["high"].toString(); // "高温 14℃"
            QString lowStr = dayObj["low"].toString();   // "低温 10℃"

            weather.highTempStr = highStr;
            weather.lowTempStr = lowStr;

            // 提取温度数值
            highStr.remove("高温").remove("℃").trimmed();
            lowStr.remove("低温").remove("℃").trimmed();

            weather.highTemp = highStr.toInt();
            weather.lowTemp = lowStr.toInt();

            weatherList.append(weather);
}
        return weatherList;
}
